<template>
  <div class="sync-order-wrapper">
    <a-button @click="handleClick" type="primary" status="warning">同步订单</a-button>
    <!-- 同步弹窗 -->
    <a-modal
      :visible="visible"
      @before-open="handleBeforeOpen"
      @close="onClose"
      @ok="onConfirm"
      @cancel="onClose"
      :mask-closable="false"
      :ok-loading="okLoading"
      :body-style="{ padding: '0px 0px' }"
      title="同步订单"
      unmount-on-close
      width="45vw"
    >
      <a-alert style="font-size: 12px" class="mb-4">
        <template #icon>
          <icon-exclamation-circle />
        </template>
        点击确认后，将从选择的时间到当前时间进行同步；
      </a-alert>
      <div class="sync-content">
        <page-form ref="formRef" :model="form" :rules="rules" auto-label-width>
          <page-form-row :gutter="24">
            <page-form-item label-align="right" field="id" label="渠道账号" required size="1">
              <a-select style="width: 270px" v-model="form.id" placeholder="请选择" popup-container="#app">
                <a-option v-for="item in channelTypeList" :value="item.id" :key="item.id" :disabled="item.status == 2">
                  {{ item.sourceName }} - {{ item.subject }}
                  <a-tag color="gray" size="small" v-if="item.status == 2">{{ item.statusName }}</a-tag>
                </a-option>
              </a-select>
            </page-form-item>
            <page-form-item label-align="right" field="startTime" label="同步下单时间在" required size="1">
              <i-date-picker
                style="margin-right: 8px"
                v-model="form.startTime"
                @popup-visible-change="handlePopupVisibleChange"
                shortcuts-position="right"
                :shortcuts="shortcuts"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                :disabledTime="getDisabledTime"
                :time-picker-props="{
                  format: 'HH:mm:ss',
                }"
                popup-container="#app"
              />
              之后的订单
            </page-form-item>
          </page-form-row>
        </page-form>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
  import { ref } from 'vue'
  import { getChannelAccount } from '@/api/order/sOrder'
  import { syncOrder } from '@/api/business/ota'
  import dayjs from 'dayjs'
  import { Message } from '@arco-design/web-vue'
  import useUserStore from '@/store/modules/user'

  const visible = ref(false)
  const userStore = useUserStore()
  const formRef = ref()
  const form = ref<any>({
    id: '',
    startTime: null,
  })
  const rules = {
    id: { required: true, message: '请选择' },
    startTime: { required: true, message: '请选择' },
  }
  const shortcuts = [
    {
      label: '当天',
      value: () => dayjs().format('YYYY-MM-DD 00:00:00'),
    },
    {
      label: '近7天',
      value: () => dayjs().subtract(7, 'day').format('YYYY-MM-DD 00:00:00'),
    },
    {
      label: '近15天',
      value: () => dayjs().subtract(15, 'day').format('YYYY-MM-DD 00:00:00'),
    },
    {
      label: '近30天',
      value: () => dayjs().subtract(30, 'day').format('YYYY-MM-DD 00:00:00'),
    },
    {
      label: '近60天',
      value: () => dayjs().subtract(60, 'day').format('YYYY-MM-DD 00:00:00'),
    },
    {
      label: '近90天',
      value: () => dayjs().subtract(90, 'day').format('YYYY-MM-DD 00:00:00'),
    },
  ]

  const handleClick = () => {
    visible.value = true
  }

  const disabledDate = (current: string) => {
    return dayjs(current).isBefore(dayjs().subtract(91, 'day')) || dayjs(current).isAfter(dayjs())
  }

  function range(start: any, end: any) {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }

  const getDisabledTime = (current: any) => {
    if (!dayjs().isSame(dayjs(current), 'day')) {
      return {}
    }

    const hour = dayjs().hour() + 1
    const minute = dayjs().minute() + 1
    const second = dayjs().second() + 1

    if (dayjs(current).hour() < hour - 1) {
      return {
        disabledHours: () => range(hour, 24),
      }
    } else if (dayjs(current).minute() < minute - 1) {
      return {
        disabledHours: () => range(hour, 24),
        disabledMinutes: () => range(minute, 60),
      }
    } else {
      return {
        disabledHours: () => range(hour, 24),
        disabledMinutes: () => range(minute, 60),
        disabledSeconds: () => range(second, 60),
      }
    }
  }

  const handlePopupVisibleChange = (visible: boolean) => {
    if (visible) {
      if (form.value.startTime) return
      if (channelOrderMaintenanceVal.value == 1) {
        form.value.startTime = dayjs().subtract(30, 'day').format('YYYY-MM-DD 00:00:00')
      } else if (channelOrderMaintenanceVal.value == 2) {
        form.value.startTime = dayjs().subtract(7, 'day').format('YYYY-MM-DD 00:00:00')
      }
    }
  }

  // 获取渠道账号
  const channelTypeList = ref<any[]>([])
  const getChannelList = () => {
    getChannelAccount().then((res: any) => {
      channelTypeList.value = res.result?.filter((i: any) => i.status != 0 && i.isDirect != 1) || []
    })
  }

  // 商户渠道订单维护方式
  // 1 自动维护 2 手动维护
  const channelOrderMaintenanceVal = ref()
  const handleBeforeOpen = () => {
    getChannelList()
    userStore.setEpDetail((result: any) => {
      channelOrderMaintenanceVal.value = result.channelOrderMaintenance
    })
  }

  // 关闭同步弹窗
  const onClose = () => {
    formRef.value.resetFields()
    visible.value = false
  }
  // 同步弹窗点击确认
  const okLoading = ref(false)
  const onConfirm = () => {
    formRef.value.validate((error: any) => {
      if (!error) {
        okLoading.value = true
        syncOrder(form.value)
          .then(() => {
            Message.success('订单正在同步中，订单同步完成后，会发送推送通知OTA渠道订单负责人')
            visible.value = false
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    })
  }
</script>
<style lang="less" scoped>
  .sync-content {
    padding: 0 12px;
  }
</style>
